var param = {}, formId = 'queryForm', url = "/openx/boss/channelGoodsService/listChannelGoodsByPage", isInit = false;

//初始化表格
(function () {
	$(".chosen-select-no-single").chosen({disable_search_threshold: 10});

	var data = $.openx.getJsonObj(formId);
	//取个随机数查询，使第一次查询为空
	data.channelCodes = 'fdsfasxxx56236589' + '-' + new Date().getTime();
	param.channelGoods = data;
	$.openx.initTable("table", url, param);
    $("#channelCode, #channelCodeImport").yfChannel({
        url: ecp_boss_server + '/openx/boss/channelService/listChannelTree',
        refreshUrl: ecp_boss_server + '/openx/boss/channelService/refreshChannelTree',
        filter: 'leaves',
        isSearch:true
    });
})();


//格式化订单详情按钮
function showControllFormat(value, row) {
	var statusName, status;
	if(row.status == "OFF_LINE") {
		statusName = '上架';
		status = 'ON_LINE';
	} else {
		statusName = '下架';
		status = 'OFF_LINE';
	}
	var s = "<a href=\'javascript:void(0)\' onclick =\"javascript:updateGoodsStatus('" + row.channelCode + "','" + row.goodsCode + "','" + status + "')\"><button type='button' class='btn btn-outline btn-primary btn-xs'>" + statusName + "</button> </a>";
	s +=  "<a href=\'javascript:void(0)\' onclick =\"javascript:showEditWindow('" + row.channelCode + "','" + row.goodsCode + "')\"><button type='button' class='btn btn-outline btn-primary btn-xs'>编辑</button> </a>";
	s +=  "<a href=\'javascript:void(0)\' onclick =\"javascript:syncGoodsInventory('" + row.channelCode + "','" + row.goodsCode + "')\"><button type='button' class='btn btn-outline btn-primary btn-xs'>库存同步</button> </a>";
	return s;
}

function showFormatStatus(value, row) {
	var statusName, status;
	if(row.status == "OFF_LINE") {
		statusName = '下架';
	} else {
		statusName = '上架';
	}
	return statusName;
}

function updateGoodsStatus(channelCode, goodsCode, status) {
	$X("/boss/channelGoodsService", "updateChannelGoodsStatus").callx({
		channelCode : channelCode,
		goodsCode : goodsCode,
		status : status,
        onResult: function (result) {
        	refreshTable();
        },
        onError: function (error) {
        }
    });
}
function syncGoodsInventory(channelCode, goodsCode) {
	$X("/boss/channelGoodsService", "syncGoodsInventory").callx({
		channelCode : channelCode,
		goodsCode : goodsCode,
		onResult: function (result) {
			refreshTable();
		},
		onError: function (error) {
		}
	});
}

function search() {
	if(!isInit) {
		isInit = true;
		
	}
	var channelList_data = $("#channelCode").yfChannel("getData");
    if (channelList_data.length == 0) {
    	layer.msg("请选择渠道！");
    	return ;
	}

	var searchGoodsCode = $('#searchGoodsCode').val();
	searchGoodsCode = searchGoodsCode ? searchGoodsCode.trim() : searchGoodsCode;

	if (!searchGoodsCode && channelList_data.length > 300) {
    	layer.msg("渠道数量超过最大值300，填写商品编码无此限制");
    	return ;
    }
	refreshTable();
}

function refreshTable() {
	var channelCode = [];
	var channelList_data = $("#channelCode").yfChannel("getData");
    if (channelList_data.length > 0) {
        $.each(channelList_data, function (i,item){
        	channelCode.push(item.displayChannel);
        });
    }
	$("#channelCodes").val(channelCode.join(","));
	
	var data = $.openx.getJsonObj(formId);
	if(data.goodsCodes.length > 0) {
		data.goodsCode = data.goodsCodes;
	}
	param.channelGoods = data;
	$.openx.initTable("table", url, param);
}

function updateBatchGoodsStatus(status) {
	var arrays = $.openx.getSelectedRow();
	if(arrays == ""){
		layer.msg("请选择商品！");
		return;
	}
	$X("/boss/channelGoodsService", "updateBatchChannelGoodsStatus").callx({
		channelGoodsDetailList : arrays,
		status : status,
        onResult: function (result) {
        	refreshTable();
        },
        onError: function (error) {
        }
    });
}

function showEditWindow(channelCode, goodsCode) {
	$X("/boss/channelGoodsService", "getChannelGoodsDetail").callx({
		channelCode : channelCode,
		goodsCode : goodsCode,
        onResult: function (result) {
        	console.log(result);
        	var html = $.openx.innerHtml('editFormTemplate');
        	laytpl($.openx.innerHtml('editFormTemplate')).render(result, function (html) {
                $.openx.openLayer('[auto, 700]', '编辑渠道 商品', html, true, function() {
                	validatorForm();
                	if($("#editForm").valid()) {
                		saveChannelGoods();
                	}
                });
            });
        },
        onError: function (error) {
        }
    });
}

function saveChannelGoods() {
	var data = $.openx.getJsonObj('editForm');
	$X("/boss/channelGoodsService", "updateChannelGoods").callx({
		channelGoods : data,
        onResult: function (result) {
        	layer.closeAll();
        	refreshTable();
        },
        onError: function (error) {
        }
    });
}

function validatorForm() {
	$("#editForm").validate({
		rules: {
			channelGoodsCode: {
		      required: true,
		      minlength: 2
		    },
		    channelGoodsName : "required",
		    guidePrice : {
		    	required : true,
		    	number : true
		    },
		    channelPrice :  {
		    	required : true,
		    	number : true
		    },
		     recommendIndex : {
		     	number : true
		     }
		    // goodsMark : "required"
		  }
	});
}

function deleteChannelGoods() {
	$.openx.onClickDelete(function(rows){
		var ids = new Array();
		for (var i = 0; i < rows.length; i++) {
			ids.push(rows[i].id);
		}
		$X("/boss/channelGoodsService", "deleteChannelGoods").callx({
			id : ids,
	        onResult: function (result) {
	        	layer.closeAll();
	        	refreshTable();
	        },
	        onError: function (error) {
	        }
	    });
	});
}

function showImportExcel() {
	/*var html = $.openx.innerHtml('uploadFileTemplate');
	html += '<script type="text/javascript">$("#channelCodeImport").yfChannel({url: "/boss/channelService/listChannelTree",filter: "leaves"});</script>';
	var data = {};
	laytpl(html).render(data, function (html) {
        $.openx.openLayer('[500, 600]', '上传渠道商品', html, true, function() {
        	importExcel();
        });
	});*/
	$("#uploadImgResult").html("");
	$("#excelFileInput").val("");
	$("#channelCodeImport").yfChannel("reset");
	$("#import-form").modal("show");
}

//检查文件大小和扩展名
function checkFileSizeType(fileId, maxFileSize, fileTypeArr) {
    var file = document.getElementById(fileId).files[0];
    if (!file) {
    	layer.tips("请选择文件！","#excelFileInput",{
			tips:[2,"#f40"]
		})
        return -1;
    }
    //检查文件类型
    if (fileTypeArr && fileTypeArr.length > 0) {
        for (var i = 0; i < fileTypeArr.length; i++) {
            fileTypeArr[i] = fileTypeArr[i].toLowerCase();
        }
        if (fileTypeArr.indexOf(file.name.substring(file.name.lastIndexOf("."), file.name.length).toLowerCase()) === -1) {
            layer.tips("上传文件类型错误！","#excelFileInput",{
    			tips:[2,"#f40"]
    		})
    		return -1;
        }
    }
    //检查文件大小
    if (file.size > maxFileSize) {
        layer.tips("上传文件不能大于" + (maxFileSize / 1024 ).toFixed(2) + "KB！","#excelFileInput",{
			tips:[2,"#f40"]
		})
		return -1;
    }
}

function importExcel(){	
	var importChannelCodeList = [];
    var channelList_data = $("#channelCodeImport").yfChannel("getData");
    if (channelList_data.length > 0) {
         $.each(channelList_data, function (i,item){
       	  importChannelCodeList.push(item.displayChannel);
         });
    };
	if(importChannelCodeList == ''){
		layer.tips("请选择渠道","#channelCodeImport",{
			tips:[2,"#f40"]
		})
		 return;
	}
	//判断文件大小
	if(checkFileSizeType('excelFileInput', 3*1024*1024, ['.xlsx','.xls'])==-1){
		return;
	}
	
	loadFileDataToBase64String('excelFileInput',function(excel){ 
		$("#importExcelButton").attr("disabled", true);
				
		$X("/boss/channelGoodsService", "importExcel").callx({
			base64Str : excel,
			channelCodes : importChannelCodeList,
			onResult : function(data) {
				$("#importExcelButton").attr("disabled", false);
				if(data && data.length > 0) { 
					$('#uploadImgResult').html(data);
				} else {
					$('#uploadImgResult').html("已加入导入队列!!!");
				}
           },
           //请求失败执行
           onError : function(error) {
        	   $("#importExcelButton").attr("disabled", false);
               var res = JSON.parse(error);
               $('#uploadImgResult').html(res.message);
               layer.msg(res.message)
           }
       }, 86400*1000);
	});    	
}

function activityTimeFormat(value, row){
    
    var beginTime = row.activityBeginTime;
    var endTime = row.activityEndTime;
    if(beginTime == undefined || endTime == undefined){
        return "-";
    }

    return $.openx.formatDate(new Date(beginTime), "yyyy-MM-dd hh:mm")+" - "+$.openx.formatDate(new Date(endTime), "yyyy-MM-dd hh:mm"); 
}

function loadFileDataToBase64String(fileName, callback) {
	var file = document.getElementById(fileName).files[0];
    //读取文件
    var reader = new FileReader();
    reader.onload = function () {
        var result = this.result.split('base64,')[1];
        callback(result);
    }
    reader.readAsDataURL(file);
}

function resetForm() {
	$("#goodsCodes").val("");
	$('#queryForm')[0].reset();
	$("#channelCode").yfChannel("reset");
}

function formatCode(value, row) {
    if(value) {
        return '\'' + value;
    } else {
        return '';
    }
}

function importDeleteExcel(){
	if(checkFileSizeType('excelDeleteFileInput', 3*1024*1024, ['.xlsx','.xls'])==-1){
		return;
	}
	loadFileDataToBase64String('excelDeleteFileInput',function(excel){ 
		$X("/boss/channelGoodsService", "importDeleteExcel").callx({
			base64Str : excel,
			onResult : function(data) {
				$("#goodsCodes").val(data);
				$("#import-delete-form").modal("hide");
				search();
           },
           //请求失败执行
           onError : function(error) {
//        	   $("#importExcelButton").attr("disabled", false);
//               var res = JSON.parse(error);
//               $('#uploadImgResult').html(res.message);
//               layer.msg(res.message)
           }
       }, 86400*1000);
	});
	
}

function showImportDeleteExcel() {
	$("#excelDeleteFileInput").val("");
	$("#import-delete-form").modal("show");
}
